<?php

namespace App\Console\Commands\Kms;

use App\Models\Kms\KmsIosCode;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportIosDownloadCode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'kms:importIosDownloadCode';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入夸父运营IOS下载code';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '2048M');

        $url = $this->ask('请输入excel地址');

        if (!$url) {
//            $url = 'https://file.51kuafu.com/b8/75/cb631f73e3a88d8b16fbf2468378d49c287e8be54679f316739a928cdb34.xls';
        }

        // 获取在线文件内容
        $tempData = (new Client())->request("get", $url)->getBody()->getContents();

        // 重命名文件
        $fileName = 'php_import_' . md5($url) . '_' . date('YmdHis', time()) . "." . array_reverse(explode('.', $url))[0];

        // 文件存储的路径
        $savePath = sys_get_temp_dir() . '/' . $fileName;

        // 存文件
        file_put_contents($savePath, $tempData);

        Excel::import(new KmsIosDownloadCode(), $savePath);

        // 删除文件
        @unlink($savePath);
    }
}

class KmsIosDownloadCode implements ToCollection
{

    private string $errMsg = '';

    private array $ratingArr = [];

    public function collection(Collection $collection)
    {
        // 校验列名信息
        $this->checkHeader($collection->first());

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        $num = 0;
        $collection->chunk(10)->map(
            function ($chunk) use (&$num) {
                $chunk->map(
                    function ($item, $row) use (&$num) {
                        $row = $row + 1;

                        if ($row == 1) {
                            return null;
                        }
                        // 常规内容校验
                        list(
                            $code,
                            $url,
                            ) = $item;


                        $kmsIosCode            = new KmsIosCode();
                        $kmsIosCode->code      = (string)$code;
                        $kmsIosCode->url       = (string)$url;
                        $kmsIosCode->createdAt = time();
                        $kmsIosCode->save();

                        //添加到redis中
                        Redis::sAdd(KmsIosCode::KMS_IOS_DOWNLOAD_CODE, (string)$code);

                        dump(++$num);
                    }
                )->filter();
            }
        );

        dump($this->ratingArr);
    }

    private function checkHeader(Collection $item)
    {
        $formColumn = [
            "代码",
            "链接",
        ];

        foreach ($formColumn as $k => $v) {
            $dataV = $item[$k] ?? '';

            if (strpos($dataV, $v) === false) {
                $this->errMsg .= sprintf("第%d列，列名错误。应为：%s，传入：%s", $k + 1, $v, $dataV) . PHP_EOL;
            }
        }
    }

}
